$(function() {
    validateKickout();
    validateRule();
    $('.imgcode').click(function() {
        var url = ctx + "captcha/captchaImage?type=" + captchaType + "&s=" + Math.random();
        $(".imgcode").attr("src", url);
    });
});

$.validator.setDefaults({
    submitHandler: function() {
        var keys = getKeys();
        if (keys){
            login();
        }
    }
});

function login() {
    $.modal.loading($("#btnSubmit").data("loading"));
    var publicKey= $.common.trim($("input[name='publicKey']").val());
    var username = $.common.trim($("input[name='username']").val());
    var password = $.common.trim(encrypt(publicKey,$("input[name='password']").val()));
    var phonenumber = $.common.trim($("input[name='phonenumber']").val());
    var smsCode = $.common.trim($("input[name='smsCode']").val());
    var validateCode = $("input[name='validateCode']").val();
    var rememberMe = $("input[name='rememberme']").is(':checked');
    $.ajax({
        type: "post",
        url: ctx + "signin",
        data: {
            "username": username,
            "password": password,
            "phonenumber": phonenumber,
            "smsCode": smsCode,
            "validateCode": validateCode,
            "rememberMe": rememberMe
        },
        success: function(r) {
            if (r.code == web_status.SUCCESS) {
                location.href = ctx + 'index';
            } else {
                $.modal.closeLoading();
                $('.imgcode').click();
                if(r.msg === "手机验证码错误"){
                    $(".smscode").val("");
                }
                $(".code").val("");
                $.modal.msg(r.msg);
            }
        }
    });
}

function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            },
            phonenumber: {
                required: true,
                isMobile: true,
                number: true,
                maxlength: 11
            },
            smsCode:{
                required: true,
                number: true
            },
            validateCode: {
                required: true
            }
        },
        messages: {
            username: {
                required: icon + "请输入您的用户名",
            },
            password: {
                required: icon + "请输入您的密码",
            },
            validateCode: {
                required: icon + "请输入图形验证码",
            },
            phonenumber: {
                required: icon + "请输入手机号码",
                isMobile: icon + "请输入正确手机号码",
                number: icon + "请输入正确手机号码",
                maxlength: icon + "请输入正确手机号码"
            },
            smsCode: {
                required: icon + "请输入短信验证码",
                number: icon + "验证码非法"
            }
        }
    })

}

function validateKickout() {
    if (getParam("kickout") === 1) {
        layer.alert("<font color='red'>您已在别处登录，请您修改密码或重新登录</font>", {
                icon: 0,
                title: "系统提示"
            },
            function(index) {
                //关闭弹窗
                layer.close(index);
                if (top != self) {
                    top.location = self.location;
                } else {
                    var url  = location.search;
                    if (url) {
                        var oldUrl = window.location.href;
                        var newUrl = oldUrl.substring(0, oldUrl.indexOf('?'));
                        self.location = newUrl;
                    }
                }
            });
    }
}

jQuery.validator.addMethod("isMobile", function(value, element) {
    var length = value.length;
    var mobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    return this.optional(element) || (length === 11 && mobile.test(value));
}, "请正确填写您的手机号码");


function getParam(paramName) {
    var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}

// RSA前端加密
function encrypt(key, oldPwd) {
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey(key);
    var encrypted = encrypt.encrypt(oldPwd);
    return encrypted;
}

//获取短信验证码
function getSmsCode(type){
    var phonenumber = $.common.trim($("input[name='phonenumber']").val());
    if(type === 'reset'){
        phonenumber = $.common.trim($("input[name='userMobile']").val());
    }
    var mobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    if(phonenumber !== null){
        if(phonenumber.length === 11 && mobile.test(phonenumber)){
            $.ajax({
                type: "post",
                url: ctx + "getSmsCode",
                data: {
                    "phonenumber": phonenumber
                },
                success: function(res) {
                    console.log(res)
                    if (res.code === 0) {
                        $.modal.closeLoading();
                        $.modal.msg("验证码已发送！")
                        if(type === 'login'){
                            sendCode();
                        }else{
                            sendCode2();
                        }
                    }else{
                        $.modal.msg(res.msg)
                    }
                }
            });
        }else{
            $.modal.closeLoading();
            $.modal.msg("手机号码不正确")
        }
    }else{
        $.modal.closeLoading();
        $.modal.msg("请输入手机号码")
    }
}

var timeClock;
function sendCode() {
    var timer_num = 60;
    timeClock=setInterval(function(){
        timer_num--;
        $("#smsCode").attr("disabled",true).text(timer_num+"秒后重新获取")
        if (timer_num === 0) {
            clearInterval(timeClock);
            $("#smsCode").attr("disabled",false).text("点击获取验证码");
        }
    },1000)
}

var timeClock2;
function sendCode2() {
    var timer_num = 60;
    timeClock2=setInterval(function(){
        timer_num--;
        $(".smsCode").attr("disabled",true).text(timer_num+"秒后重新获取")
        if (timer_num === 0) {
            clearInterval(timeClock2);
            $(".smsCode").attr("disabled",false).text("点击获取验证码");
        }
    },1000)
}

$(document).ready(function () {
    $(".loginContent").show();
    $(".resetPassword").hide();
    $(".renewPassword").hide();
})

//忘记密码
function forgetPwd(){
    $(".loginContent").hide();
    $(".resetPassword").show();
}

// 中途返回登录界面
$("#lastStep").on("click",function () {
    window.document.location.reload();
})

var nextStep = false;
var success = "<i class='fa fa-check' style='color:green;float: left;margin-bottom: 5px;'></i>";
var error = "<i class='fa fa-times-circle' style='color: red;'></i> ";
//校验用户名是否存在
function checkSignInNo(){
    let signInNo = $.common.trim($("input[name='signInNo']").val());
    if(signInNo != null){
        $.ajax({
            type: "get",
            url: ctx + "checkSignInNo",
            data: {
                "signInNo": signInNo
            },
            success: function(res) {
                console.log(res)
                if (res.code === 0) {
                    nextStep = true;
                    $('#hint').remove();
                    $('#signInNo').after("<label id='hint' style='color: green;'>"+success+"用户校验成功</label>")
                }else{
                    $('#hint').remove();
                    $('#signInNo').after("<label id='hint' style='color: red;'>"+error+"用户不存在</label>")
                }
            }
        });
    }else {
        $('#hint').remove();
        $('#signInNo').after("<label style='color: red;'>"+error+"手机号码不正确</label>")
    }
}

// 手机号校验
function checkUserMobile(){
    var userMobile = $.common.trim($("input[name='userMobile']").val());
    var mobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    if(userMobile !== null) {
        if (userMobile.length === 11 && mobile.test(userMobile)) {
            nextStep = true;
            $('#hint1').remove();
            $('#userMobile').after("<label id='hint1' style='color: green;'>"+success+"手机号码校验成功</label>")
        }else{
            nextStep = false;
            $('#hint1').remove();
            $('#userMobile').after("<label id='hint1' style='color: red;'>"+error+"手机号码不正确</label>")
        }
    }
}

//验证手机号码/用户名
$('#nextStep').on('click',function () {
    nextStepValidate();
})

function nextStepValidate() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#resetPassword").validate({
        rules: {
            signInNo: {
                required: true
            },
            userMobile: {
                required: true,
                isMobile: true,
                number: true,
                maxlength: 11
            },
            userCode:{
                required: true,
                number: true
            }
        },
        messages: {
            signInNo: {
                required: icon + "请输入需要修改的登录名",
            },
            userMobile: {
                required: icon + "请输入手机号码",
                isMobile: icon + "请输入正确手机号码",
                number: icon + "请输入正确手机号码",
                maxlength: icon + "请输入正确手机号码"
            },
            userCode: {
                required: icon + "请输入短信验证码",
                number: icon + "验证码非法"
            }
        },
        submitHandler:function () {
            let signInNo = $.common.trim($("input[name='signInNo']").val());
            let userMobile = $.common.trim($("input[name='userMobile']").val());
            let userCode = $.common.trim($("input[name='userCode']").val());
            if(signInNo !== '' && userMobile !== '' && userCode !== ''){
                //校验
                $.modal.loading($("#nextStep").data("loading"));
                $.ajax({
                    type: "get",
                    url: ctx + "checkMobileCode",
                    data: {
                        "signInNo": signInNo,
                        "userMobile": userMobile,
                        "userCode": userCode
                    },
                    success: function (res) {
                        $.modal.closeLoading();
                        if(res.code === 0 && nextStep){
                            $(".resetPassword").hide();
                            $(".renewPassword").show();
                        }else{
                            $.modal.msgError("验证码错误，请重试")
                        }
                    }
                });
            }
        }
    })
}

//设置新密码 校验两次密码是否一致
var isReset = false;

function setError() {
    $('#hint2').remove()
    $('#hint3').remove()
}

//提交更改
$('#affirm').on('click',function () {
    affirmValidate();
})
jQuery.validator.addMethod("newpwdRule", function(value, element) {
    var length = value.length;
    let checkPwd = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/;
    return this.optional(element) || (length > 0 && checkPwd.test(value));
}, "必须包含数字、大小写字母，长度8-15");
jQuery.validator.addMethod("isAccord", function(value, element) {
    let newPwd2 = $.common.trim($("input[name='newPwd2']").val());
    return this.optional(element) || value === newPwd2
}, "两次输入不一致");
function affirmValidate() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#renewPassword").validate({
        rules: {
            newPwd1: {
                required: true,
                newpwdRule: true
            },
            newPwd2: {
                required: true,
                newpwdRule: true,
                isAccord: true
            }
        },
        messages: {
            newPwd1: {
                required: icon + "请输入密码",
                newpwdRule: icon + "必须包含数字、大小写字母，长度8-15"
            },
            newPwd2: {
                required: icon + "请再次输入密码",
                newpwdRule: icon + "必须包含数字、大小写字母，长度8-15",
                isAccord: icon + "两次输入不一致"
            }
        },
        submitHandler:function () {
            let newPwd1 = $.common.trim($("input[name='newPwd1']").val());
            let newPwd2 = $.common.trim($("input[name='newPwd2']").val());
            let signInNo = $.common.trim($("input[name='signInNo']").val());
            if(newPwd1 !== newPwd2){
                $('#hint3').remove()
                $('#newPwd2').after("<label id='hint3' style='color: red;'>"+error+"两次输入不一致</label>")
            }else{
                isReset = true;
                $('#hint3').remove()
                if(isReset){
                    $.modal.confirm("确认重置用户："+signInNo+" 的登录密码？",function () {
                        $.modal.loading($("#affirm").data("loading"));
                        let publicKey= $.common.trim($("input[name='publicKey']").val());
                        let newPwd = encrypt(publicKey,newPwd2)
                        $.ajax({
                            type: "post",
                            url: ctx + "resetPassword",
                            data: {
                                'resetUsername': signInNo,
                                'newPassword': newPwd
                            },
                            success: function (res) {
                                $.modal.closeLoading();
                                if(res.code === 0){
                                    $.modal.msgSuccessReload("密码修改成功，请重新登录！")
                                }else{
                                    $.modal.msgError("重置失败，请重试")
                                }
                            }
                        });
                    })
                }
            }
        }
    })
}

//获取密钥
function getKeys() {
    let exURL = "/getKeys";
    var isGetKeys=false;
    $.ajax({
        type: "post",
        async: false,
        url: exURL,
        success: function(result) {
            if (result.code == web_status.SUCCESS) {
                $("#publicKey").val(result.msg);
                isGetKeys=true;
            } else {
                $.modal.msgError(result.msg);
            }
        }
    });
    return isGetKeys;
}

